%%%-------------------------------------------------------------------
%%% @author Anil Kumar S. R. <sranil@gmail.com>
%%% @copyright (C) 2010, 
%%% @doc
%%%
%%% @end
%%% Created : 10 Oct 2010 by Anil Kumar S. R. <sranil@gmail.com>
%%%-------------------------------------------------------------------
-module(utils).
-export([generate_random_string/0, generate_random_number/1, replace_character_to_predefined_xml_entities/1, replace_predefined_xml_entities_to_character/1]).

-define(ALPHA_NUMERIC_CHARS, {$A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M, $N, $O, $P, $Q, $R, $S, $T, $U, $V, $W, $X, $Y, $Z, $0, $1, $2, $3, $4, $5, $6, $7, $8, $9}).

generate_random_string() ->
    First_Random_Number = generate_random_number(16#FFFFFFFFFFFFFFFF),
    Second_Random_Number = generate_random_number(16#FFFFFFFFFFFFFFFF),
    convert_byte_to_char([], <<First_Random_Number:64>>) ++ convert_byte_to_char([], <<Second_Random_Number:64>>).

generate_random_number(Max_Num) ->
    {A, B, C} = erlang:now(),
    random:seed(A, B, C),
    random:uniform(Max_Num).

convert_byte_to_char(List, <<>>) ->
    List;

convert_byte_to_char(List, Random_Number) ->
    <<Head:8, Rest/binary>> = Random_Number,
    Character = element((Head rem 36) + 1, ?ALPHA_NUMERIC_CHARS),
    convert_byte_to_char([Character|List], Rest).

replace_character_to_predefined_xml_entities(Data) ->
    A1 = re:replace(Data, [$&], ["\\&amp;"], [{return, list}]),
    A2 = re:replace(A1, [$<], ["\\&lt;"], [{return, list}]),
    A3 = re:replace(A2, [$>], ["\\&gt;"], [{return, list}]),
    A4 = re:replace(A3, [$"], ["\\&quot;"], [{return, list}]),
    re:replace(A4, [$'], ["\\&apos;"], [{return, list}]).

replace_predefined_xml_entities_to_character(Data) ->
    A1 = re:replace(Data, ["\\&lt;"], [$<], [{return, list}]),
    A2 = re:replace(A1, ["\\&gt;"], [$>], [{return, list}]),
    A3 = re:replace(A2, ["\\&quot;"], [$"], [{return, list}]),
    A4 = re:replace(A3, ["\\&apos;"], [$'], [{return, list}]),
    A5 = re:replace(A4, ["\\&amp;"], [$&], [{return, list}]),
    lists:flatten(A5).
